import math

from django.core import serializers
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect

# Create your views here.

# 1849569749@qq.com
# w1849569749@163.com
from django.template import loader
from django.views import View

from SentEmail import SendEmail
from user.models import UserInfo, Suggest


class Login(View):
    def get(self, request):
        error = request.GET.get('sign')
        name = request.GET.get('username')
        # print(name)
        return render(request, 'login.html', {"error": error, 'username': name})

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            user = UserInfo.objects.filter(email=username)

            if username == user[0].email and password == user[0].password:
                request.session['user'] = username  # 存入session
                # print(request.session['user'])
                return redirect('/index/')
            else:
                return redirect('/login?sign=' + "error&username=" + username)
        except:
            return redirect('/login?sign=' + "error&username=" + username)


class Register(View):
    def get(self, request):
        if request.method == 'GET':
            sign = request.GET.get('sign')
            username = request.GET.get('username')
            password = request.GET.get('password')
            # print(sign, username, password)
            if sign == 'click':
                email_data = {
                    # mlvfavfzgmsmfcgc
                    'sender': "wx.0199@qq.com",  # 发送者邮箱，自己用可写死
                    'password': "efxmmwxfpiaobhea",  # 在开启SMTP服务后，可以生成授权码，此处为授权码
                    'subject': "四菜一汤验证码",  # 邮件主题名，没有违规文字都行
                    'name': username
                }
                global verification
                try:
                    verification = SendEmail(data=email_data, receiver=username).send_email()
                    print(verification)
                    return JsonResponse({'flag': True})
                except:
                    return JsonResponse({'flag': False})

            repetition = request.GET.get('repetition')
            if repetition == 'true':
                return render(request, 'register.html', {"repetition": 'true'})
        return render(request, 'register.html')

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        re_pwd = request.POST.get('re_password')
        # print(username, password, re_pwd)
        check_num = request.POST.get('checkNum')
        # print(check_num)
        user = UserInfo.objects.filter(email=username)
        # print(user)
        if not user.exists():
            try:
                if check_num == verification:
                    UserInfo.objects.create(name=username, email=username, password=password,
                                            profilePhoto='/media/img.png')
                    request.session['user'] = username
                    return redirect('/index')
                else:
                    return render(request, 'register.html',
                                  {"username": username, 'password': password, 're_pwd': re_pwd, 'sign': "error"})
            except:
                return render(request, 'register.html',
                              {"username": username, 'password': password, 're_pwd': re_pwd,
                               'check': False})
        else:
            return redirect('/register/?repetition=' + 'true')


class Personal(View):
    def get(self, request):
        try:
            login = request.session['user']
            # print(login)
            if login:
                userinfo = UserInfo.objects.filter(email=login)
                suggests = Suggest.objects.filter(email=login)
                pagelist = range(1, math.ceil(len(suggests) / 4) + 1)
                max_page = max(pagelist)
                page = request.GET.get('page')
                # print(page)
                if page:
                    page = int(page)
                else:
                    page = 1
                suggests = suggests[(page - 1) * 4:page * 4]
                if request.is_ajax():
                    suggests = serializers.serialize("json", suggests)
                    return JsonResponse({'login': 'true', 'suggests': suggests, 'page': page, 'max_page': max_page})
                return render(request, 'personal.html',
                              {'login': 'true', 'personal': 'true', 'userinfo': userinfo, 'suggests': suggests,
                               'page': page, 'max_page': max_page})
            return render(request, 'personal.html', {'personal': 'true'})  # {'name': name}
        except:
            return redirect('/index')

    def post(self, request):
        try:
            suggest = request.POST.get('suggest')
            if suggest:
                try:
                    email = request.session['user']
                    # print(email.aaa)
                    userinfo = UserInfo.objects.filter(email=email).values()
                    Suggest.objects.create(email=email, name=userinfo[0]['name'],
                                           profilePhoto=userinfo[0]['profilePhoto'], content=suggest)
                    return JsonResponse({'sign': 'success'})
                except:
                    return JsonResponse({'sign': "fault"})
            else:
                img_src = request.FILES['get_headPhoto']
                with open('media/' + img_src.name, mode='wb') as f:
                    for chunk in img_src.chunks():
                        f.write(chunk)
                    f.close()
                user = request.session['user']
                userinfo = UserInfo.objects.filter(email=user)
                other = Suggest.objects.filter(email=user)
                userinfo.update(profilePhoto='/media/' + img_src.name)
                other.update(profilePhoto='/media/' + img_src.name)
                return redirect('/personal/')
        except:
            return redirect('/personal/')


class Logout(View):
    def get(self, request):
        sign = request.GET.get('sign')
        if sign == 'click':
            # print(sign)
            del request.session['user']
            return redirect('/index')
        else:
            return redirect('/index')
